package co.baiku.boot.core.orm.spring;

import co.baiku.boot.common.spring.SpringBootInfoTentacle;
import co.baiku.boot.common.spring.SpringContext;
import co.baiku.boot.common.tools.AnnotationTools;
import co.baiku.boot.common.tools.ObjectTools;
import org.springframework.data.jpa.repository.config.EnableJpaRepositories;
import org.springframework.stereotype.Component;

import java.lang.annotation.Annotation;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Map;

/**
 * orm包扫描包上报
 */
@Component
public class SpringBootInfoOrmTentacle implements SpringBootInfoTentacle {

    @Override
    public List<String> getScanPackages() {
        List<String> result = new ArrayList<>();
        Map<String, Object> enableJpaRepositoriesMap = SpringContext.getBeansWithAnnotation(EnableJpaRepositories.class);
        if (ObjectTools.isNotBlank(enableJpaRepositoriesMap)) {
            enableJpaRepositoriesMap.forEach((k, v) -> {
                Annotation classAnnotation = AnnotationTools.findClassAnnotation(v.getClass(), EnableJpaRepositories.class);
                if (classAnnotation != null && ((EnableJpaRepositories) classAnnotation).basePackages().length > 0) {
                    List<String> pkgs = Arrays.asList(((EnableJpaRepositories) classAnnotation).basePackages());
                    result.addAll(pkgs);
                }
            });
        }
        return result;
    }
}
